<?php

namespace app\model;

use Exception;
use support\Log;
use yzh52521\EasyHttp\Http;

/**
 *Wxbot类
 */
class Wxbot
{

    /**
     * 发送文本消息
     * @param $wxid
     * @param $content
     * @return array|mixed
     */
    public static function sendTextMsg($wxid, $content): mixed
    {
        $response = Http::asJson()->post(Config::getApiBaseUrl() . '/api/sendtxtmsg', ['wxid' => $wxid, 'content' => $content]);
        $result = $response->array();
        Log::info('发送文本消息结果：', $result);
        return $result;
    }

    /**
     * 获取转发消息的wxid
     * @param $msg_content
     * @return array
     */
    public static function getForwardWxid($msg_content): array
    {
        try {
            $rules = (new ForwardRule())->getForwardRules();
            foreach ($rules as $v) {
                if (str_contains($msg_content, $v['keyword'])) {
                    $forward_wxid = (new ForwardRule())
                        ->where('keyword', $v['keyword'])
                        ->column('forward_wxid');
                }
            }
            return $forward_wxid ?? [];
        } catch (Exception $e) {
            d($e->getMessage());
        }
    }

    /**
     * 转发消息
     * @param $wxid
     * @param $msg_id
     * @return array|mixed
     */
    public static function forwardmsg($wxid, $msg_id): mixed
    {
        $response = Http::get(Config::getApiBaseUrl() . '/api/forwardmsg?wxid=' . $wxid . '&msgId=' . $msg_id);
        $result = $response->array();
        Log::info('转发结果：', $result);
        $sql_data = [
            'wxid' => $wxid,
            'msg_id' => $msg_id,
            'result' => json_encode($result)
        ];
        (new ForwardMsgLog())->insert($sql_data);
        return $result;
    }


    /**
     * 处理管理员命令
     * @param $wxid
     * @param $msg_content
     * @return void
     */
    public static function handleAdminCmd($wxid, $msg_content)
    {
        try {
            $cmd_symbol = Config::getCmdSymbol();
            //如果消息的发送者是admin，并且消息是一个命令符号开头的，则执行命令
            if (Config::isAdmin($wxid)) {
                //更新转发规则的命令: 新增转发规则+触发词+转发的NickName
                if (str_contains($msg_content, '新增转发规则')) {
                    $rule_keyword = trim(explode('+', $msg_content)[1]);
                    $forward_wxid = trim(explode('+', $msg_content)[2]);
                    $rule_data = [
                        'keyword' => $rule_keyword,
                        'forward_wxid' => $forward_wxid,
                    ];
                    (new ForwardRule())->createOrUpdateForwardRule($rule_data);
                    $msg = '新增转发规则成功';
                    return self::sendTextMsg($wxid, $msg);
                } elseif (str_contains($msg_content, '删除转发规则')) {
                    //指定规则是：/bot删除转发规则+id
                    $rule_id = trim(explode('+', $msg_content)[1]);
                    if (ForwardRule::destroy(intval($rule_id))) {
                        $msg = '删除转发规则成功';
                    } else {
                        $msg = '删除转发规则失败';
                    }
                    return self::sendTextMsg($wxid, $msg);
                } elseif (str_contains($msg_content, '查看转发规则')) {
                    $rules = (new ForwardRule())->getForwardRules();
                    $rule = '';
                    foreach ($rules as $item) {
                        $rule .= 'ID=' . $item['id'] . ':' . $item['keyword'] . '=>' . (new Contact())->getNickNameByWxid($item['forward_wxid']);
                        //将每一条规则用换行符分隔
                        $rule .= PHP_EOL;
                    }
                    //删除最后一个换行符
                    $rule = rtrim($rule, PHP_EOL);
                    if (empty($rule)) {
                        $rule = '暂无转发规则';
                    }
                    return self::sendTextMsg($wxid, $rule);
                } elseif (str_contains($msg_content, '查询微信号')) {
                    $keyword = trim(explode('+', $msg_content)[1]);
                    $result = (new Contact())->getUserNameByNickNameKeyword($keyword);
                    return self::sendTextMsg($wxid, $result);
                } elseif (str_contains($msg_content, '查看指令')) {
                    $msg = '可用指令如下：' . PHP_EOL . $cmd_symbol . '新增转发规则+触发词+微信号' . PHP_EOL . $cmd_symbol . '删除转发规则+id' . PHP_EOL . $cmd_symbol . '查看转发规则' . PHP_EOL . $cmd_symbol . '查看指令' . PHP_EOL . $cmd_symbol . '查询微信号+关键字';
                    return self::sendTextMsg($wxid, $msg);
                } else {
                    return self::sendTextMsg($wxid, '无效指令!' . PHP_EOL . '发送：【' . $cmd_symbol . '查看指令】可以查看可用指令');
                }
            }
        } catch (Exception $e) {
            Log::error('处理管理员命令失败：' . $e->getMessage());
            return self::sendTextMsg($wxid, '处理管理员命令失败：' . $e->getMessage());
        }
    }
}
